package com.wu.leetcode.leetcode106;

/**
 * Leetcode106-从中序与后序遍历序列构造二叉树
 *
 * @author lynn
 * @date 2020/8/7 - 16:59
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return reConstruct(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    private TreeNode reConstruct(int[] inorder, int inLeft, int inRight, int[] postorder, int poLeft, int poRight) {
        if (inLeft > inRight || poLeft > poRight) {
            return null;
        }
        int rootVal = postorder[poRight];
        TreeNode node = new TreeNode(rootVal);
        int index = 0;
        for (int i = inLeft; i <= inRight; i++) {
            if (postorder[poRight] == inorder[i]) {
                index = i;
                break;
            }
        }
//        中序遍历 inorder = [9,3,15,20,7]
//        后序遍历 postorder = [9,15,7,20,3]
        node.left = reConstruct(inorder, inLeft, index - 1, postorder, poLeft, index - 1 - inLeft + poLeft);
        node.right = reConstruct(inorder, index + 1, inRight, postorder, index - inRight + poRight, poRight - 1);
        return node;
    }
}